package com.castile.functional;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @description:
 * @author: Castile
 * @create: 2024-04-16 22:36
 * @Version 1.0
 **/
public class TestFunctionObj {

    interface Lambda extends Serializable {
        int cal(int a, int b);
    }

    static class Server {
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket = new ServerSocket(9090);
            System.out.println("server start");
            while (true) {
                Socket s = serverSocket.accept();
                new Thread(() -> {
                    try {
                        ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                        Lambda lambda = (Lambda) ois.readObject();
                        int a = ThreadLocalRandom.current().nextInt(10);
                        int b = ThreadLocalRandom.current().nextInt(10);
                        System.out.printf("%s %d op %d = %d%n", s.getRemoteSocketAddress().toString(), a, b, lambda.cal(a, b));
                    } catch (IOException | ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }, "handler-thread").start();
            }

        }
    }

    static class Client0 {
        public static void main(String[] args) {
            try (Socket s = new Socket("127.0.0.1", 9090)) {
                Lambda lambda = Integer::sum;
                ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
                os.writeObject(lambda);
                os.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class Client1 {
        public static void main(String[] args) {
            try (Socket s = new Socket("127.0.0.1", 9090)) {
                Lambda lambda = (a, b) -> a * b;
                ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
                os.writeObject(lambda);
                os.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    static class Client3 {
        public static void main(String[] args) {
            try (Socket s = new Socket("127.0.0.1", 9090)) {
                Lambda lambda = (a, b) -> a - b;
                ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
                os.writeObject(lambda);
                os.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
